/*
 ============================================================================
 Name		: FbContentWindow.cpp
 Author	  : ceze
 Version	 : 1.0
 Copyright   : FlashBox for ver.Zhongyou(���ʰ�)
 Description : CFbContentWindow implementation
 ============================================================================
 */

#include "FbContentWindow.h"
#include <coemain.h>
#include "ConstDefined.hrh"
#include "Flashbox4.hrh"
#include "Flashbox4.mbg"//mbm图头文件
#include "Flashbox4_0x20021B21.rsg"
#include "rfsengine.h"
#include "FbListData.h"
#include "FbUtils.h"
#include "FlashBox4MainContainer.h"

#include <EIKENV.H>
#include <stringloader.h>
#include <APMSTD.H> 
#include <apgcli.h>
#include <APACMDLN.H>
#include <aknquerydialog.h>
#include <APGWGNAM.H>
#include <W32STD.H>

#ifdef __WINSCW__
#include <e32svr.h>   //RDebug
#endif

#define _HODE_REMOTE_STATE_
#define _SAVE_LOCAL_INFO_
#define _NOKIA_N95_Flashlite2_

CFbContentWindow::CFbContentWindow () :
	m_pProgressBar (NULL),
	m_storeType (ETypeLocal )
{
	// No implementation required
}

CFbContentWindow::~CFbContentWindow ()
{
	delete m_pLeftTabgroup;
	delete m_pContentList;
	delete m_pRfsEngine;
	delete m_pXmlHandler;
	delete m_pProgressBar;
	delete m_pDocHandler;
	delete m_pDezip;
	//delete m_pContextNodeRemote;
	delete m_pContextNodeLocal;
}

void CFbContentWindow::ConstructL (const TRect &aRect, CCoeControl *pParent )
{
	//	CreateWindowL (pParent );
	SetContainerWindowL (*pParent );
	m_pParent = pParent;

	//m_pRfsEngine
	m_pRfsEngine = CRfsEngine::NewL ();
	//m_pXmlHandler
	m_pXmlHandler = CXmlHandler::NewL (*this );

	//创建子控件
	m_pLeftTabgroup = CFbTabgroupLeft::NewLC (KFbLeftTabgroupRect, this );
	InitializeTabGroupL (m_pLeftTabgroup );
	m_pLeftTabgroup->SetActiveL ();
	m_pLeftTabgroup->SetObserver (this );
	//m_pLeftTabgroup->SetActiveTabByIndexL (0 );
	CleanupStack::Pop (m_pLeftTabgroup );// 弹出清除栈;
	

	//内容列表
	TRect listRect (aRect.iTl.iX + KFbLeftTabgroupRect.Width (), aRect.iTl.iY,
			aRect.iBr.iX, aRect.iBr.iY/* - KFbSoftKeyRect.Height () */);
	m_pContentList = CFbList::NewL (listRect, this );
	m_pContentList->SetBackground (KFbSettingRoundRectColor,
			KFbSettingRoundRectColor );
	m_pContentList->SetFocusedBackground (KFbFocusRectColor, -1 );
	m_pContentList->SetTextColor (KRgbDarkGray, KFbTabgroupTopTitleColor );
	m_pContentList->SetObserver (this );

	//LoadDataL (EPing_bao_tian_di, ETypeRemote );
	//	printf("Hello World\n");

	SetRect (aRect );
	ActivateL ();
}

/**
 * From CoeControl,CountComponentControls.
 */
TInt CFbContentWindow::CountComponentControls () const
{
	return 2;
}

/**
 * From CCoeControl,ComponentControl.
 */
CCoeControl* CFbContentWindow::ComponentControl (TInt aIndex ) const
{
	switch (aIndex )
	{
	case 0:
		return m_pLeftTabgroup;
	case 1:
		return m_pContentList;
	default:
		return NULL;
	}
}

/**
 * From CCoeControl, Draw
 * Draw this CFbTabgroup to the screen.
 * @param aRect the rectangle of this view that needs updating
 */
void CFbContentWindow::Draw (const TRect& aRect ) const
{
	// Get the standard graphics context
	CWindowGc& gc = SystemGc ();
	
	// Gets the control's extent
	TRect drawRect (Rect () );
	gc.SetPenStyle (CGraphicsContext::ENullPen );
	gc.SetBrushColor (KFbBackgroundColor );
	gc.SetBrushStyle (CGraphicsContext::ESolidBrush );
	gc.Clear (drawRect );
	
}

/**
 * From CCoeControl
 */
void CFbContentWindow::SizeChanged ()
{
	DrawNow ();
}

/**
 * 初始化Tab组件
 */
void CFbContentWindow::InitializeTabGroupL (CFbTabgroupLeft *pTabgroup )
{
	if (pTabgroup == NULL )
		return;
	for (int i = 0; i < 2; i++ )
	{
		TInt resId = EMbmFlashbox4Tabshouchang + 2 * i;
		pTabgroup->AddTabL (resId, KFlashboxImagePath, resId, resId + 1,
				EMbmFlashbox4Tabbarleft, R_TAB_LEFT_ITEM1 + i );
	}
}

/**
 * 切换内容
 */
void CFbContentWindow::SwitchContentL (TInt aContentId )
{
	if (m_pLeftTabgroup )
		m_pLeftTabgroup->NextTabL ();
}

/**
 * 栏目切换
 */
void CFbContentWindow::ChangeToCategory (const TContentsType type, const TStoreType /*aStoreType*/ )
{
	m_categoryType = type;
	m_contentsType = type;
	
#ifdef _HODE_REMOTE_STATE_
	switch (m_storeType )
	//通过m_storeType判断 , 即不更新上次所在状
#else
	switch (aStoreType)
#endif
	{
	case ETypeLocal:
		m_pLeftTabgroup->SetActiveTabByIndexL (0 );
		break;
	case ETypeRemote:
		m_pLeftTabgroup->SetActiveTabByIndexL (1 );
		break;
	default:
		break;
	}
	
}

/**
 * 加载数据,到List
 */
void CFbContentWindow::LoadDataL (TInt aConType, TStoreType aStoreType )
{
	m_contentsType = aConType;
	m_storeType = aStoreType;

	if (!m_pRfsEngine )
		m_pRfsEngine = CRfsEngine::NewL ();

	if (aStoreType == ETypeLocal ) //加载本地数据
	{
		//检索本地文件
		TFileName contentPath (KFbContentsPath );
		AddDrive (contentPath );
#ifdef _SAVE_LOCAL_INFO_
		if (m_pContextNodeLocal )
		{
			delete m_pContextNodeLocal;
			m_pContextNodeLocal = NULL;
		}
		//清除原有数据
		if (m_pContentList )
			m_pContentList->RemoveAll ();

		if (m_categoryType != m_contentsType )
		{
			contentPath.AppendFormat (_L("\\data\\%d\\%d\\info\\local.xml"), m_categoryType,
					aConType );
		}
		else
		{
			contentPath.AppendFormat (_L("\\data\\%d\\info\\local.xml"), m_categoryType );
		}
		m_pRfsEngine->EnsurePathExistsL (contentPath);
		//解析本地内容文件
		if (m_pRfsEngine->FileExist (contentPath ) )
		{
			m_pXmlHandler->StartParsingL (m_pRfsEngine->RFS (), contentPath,
					ETypeLocal );
		}
		else
		{
			CAknQueryDialog* dlg = CAknQueryDialog::NewL ();
			HBufC* msg = StringLoader::LoadLC (R_CHANGE_PROMPT_TEXT );
			if (dlg->ExecuteLD (R_CONFIRM_PROMPT, *msg ) )
			{
				CleanupStack::PopAndDestroy (1 );
				SwitchContentL (0 );
				return;
			}
			CleanupStack::PopAndDestroy (1 );
		}
#else
		////枚举文件列表方式
		if (m_categoryType != m_contentsType )
		{
			contentPath.AppendFormat (_L("\\data\\%d\\%d\\"), m_categoryType,
					aConType );
		}
		else
		{
			contentPath.AppendFormat (_L("\\data\\%d\\"), m_categoryType );
		}
		m_pRfsEngine->GetFileList (contentPath );
		TInt itemCount = m_pRfsEngine->FileCount ();
		for (TInt i = 0; i < itemCount; i++ )
		{
			CFbListData *pListItem = new (ELeave) CFbListData ();
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (m_pRfsEngine->GetFileName (i ) );
			CFbsBitmap *pIcon = (CEikonEnv::Static ())->CreateBitmapL (
					KFlashboxImagePath, EMbmFlashbox4Icon3 );
			CFbsBitmap *pIconB = (CEikonEnv::Static ())->CreateBitmapL (
					KFlashboxImagePath, EMbmFlashbox4Applogo );
			pListItem->SetItemIcons (pIcon, pIconB);
			m_pContentList->AddItemL (pListItem );
			CleanupStack::Pop ();//pListItem
		}
		m_pContentList->DrawNow();
#endif	
	}
	else //读取网络数据
	{
#ifdef _HODE_REMOTE_STATE_
#ifdef _SAVE_LOCAL_INFO_
		//读取已下载数据,以做筛选
		TFileName contentPath (KFbContentsPath );
		AddDrive (contentPath );
		if (m_pContextNodeLocal )
		{
			delete m_pContextNodeLocal;
			m_pContextNodeLocal = NULL;
		}
		//清除原有数据
		if (m_pContentList )
			m_pContentList->RemoveAll ();

		if (m_categoryType != m_contentsType )
		{
			contentPath.AppendFormat (_L("\\data\\%d\\%d\\info\\local.xml"), m_categoryType,
					aConType );
		}
		else
		{
			contentPath.AppendFormat (_L("\\data\\%d\\info\\local.xml"), m_categoryType );
		}
		m_pRfsEngine->EnsurePathExistsL (contentPath );
		//解析本地内容文件
		if (m_pRfsEngine->FileExist (contentPath ) )
		{
			m_pXmlHandler->StartParsingL (m_pRfsEngine->RFS (), contentPath,
					ETypeLocal );
		}
#endif
#endif
		//判断xml是否存在,不存在则从网络更新
		TFileName xmlPath (KFbContentsPath );
		AddDrive (xmlPath );
		if (m_categoryType != m_contentsType )
		{
			xmlPath.AppendFormat (_L("\\data\\%d\\%d\\info\\remote.xml"), m_categoryType,
					m_contentsType );
		}
		else
		{
			xmlPath.AppendFormat (_L("\\data\\%d\\info\\remote.xml"), m_categoryType );
		}
		if (m_pRfsEngine->FileExist (xmlPath ) )
		{
			//解析xml内容
			m_pXmlHandler->StartParsingL (m_pRfsEngine->RFS (), xmlPath,
					ETypeRemote );
		}
		else
		{
			//从网上更新
			QueryDataByHttpL (m_contentsType, EQueryContents );
		}
	}
}

/**
 * 更新服务器xml内容配置
 */
void CFbContentWindow::QueryDataByHttpL (const TInt aContentId, const TDataQueryTpey queryType )
{
	CXmlNode *pNode = CXmlNode::NewL (KContentQuery );//contentquery
	CleanupStack::PushL (pNode );
	//添加基本消息
	pNode->AddNodeL (GetMobileInfoNode () );

	if (queryType == EGetContents )//下载
	{
		m_httpQueryType = EGetContents;
		pNode->AddNodeL (KQueryType, EGetContents ); //下载内容
		pNode->AddNodeL (KItemId, aContentId );
		pNode->AddNodeL (KFeeId, 4 );//包月计费(i
	}
	else//读取xml
	{
		if (aContentId == EDong_man_shu_ba )//动漫书吧,查询
		{
			m_httpQueryType = EQueryFolders;
			pNode->AddNodeL (KQueryType, EQueryFolders ); //查询目录
			pNode->AddNodeL (KItemId, aContentId );
		}
		else
		{
			m_httpQueryType = EQueryContents;
			pNode->AddNodeL (KQueryType, EQueryContents ); //3内容查询
			pNode->AddNodeL (KItemId, aContentId );
			pNode->AddNodeL (KQueryId, 0 );//
			pNode->AddNodeL (KQueryCount, 30 );
			
		}
	}
	pNode->AddNodeL (KMainVersion, KProtocolVersion );
	//get data
	HBufC8 *postData = pNode->GetXMLStringL ();
	CleanupStack::PushL (postData );
	m_querySessionId = aContentId;
	GetAppUi ()->IssueHttpPostL (this, KFbServiceUrl, postData->Des (),
			KNullDesC8, m_querySessionId, EFalse, 100 );
	CleanupStack::PopAndDestroy (2 );//postData , pNode;	

	//显示滚动条
	StartToShowProgressBar ();
}

/**
 * 取消网络连接
 */
void CFbContentWindow::CancelHttpQueryL ()
{
	GetAppUi ()->CancelHttpQueryL ();
	StopProgressBar ();
}

/**
 * 取得内容id
 */
TInt CFbContentWindow::GetContentId ()
{
	return 0;
}

/*
 * From CoeControl,
 * 按键事件接收处理
 */
TKeyResponse CFbContentWindow::OfferKeyEventL (const TKeyEvent &aKeyEvent, TEventCode aType )
{
	if (m_pContentList )
		return m_pContentList->OfferKeyEventL (aKeyEvent, aType );
	else
		return EKeyWasNotConsumed;
}

/**
 * 派生自MFbTabObserver接口(left tab)
 * 处理tab切换事件
 */
void CFbContentWindow::TabChangedL (TInt aTabIndex, TInt /*aTabId*/)
{
	switch (aTabIndex )
	{
	case 0:
		UpdateOptionMenu (EPageLocal );
		((CFlashbox4MainContainer*) m_pParent)->SetSoftKeyBarL (
				ESoftkeybar_Option_Remote );
		LoadDataL ((TContentsType) m_contentsType, ETypeLocal );
		break;
	case 1:
		UpdateOptionMenu (EPageRemote );
		((CFlashbox4MainContainer*) m_pParent)->SetSoftKeyBarL (
				ESoftkeybar_Option_Local );
		LoadDataL ((TContentsType) m_contentsType, ETypeRemote );
		break;
	}
	((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetLabel2Text (
			KNullDesC );
	DrawNow ();
}

/**
 * from MListObserver
 * pHandle 发出消息的对象
 * aItemIndex:激活的item 序号
 * aEventType:事件类型
 */
void CFbContentWindow::ListItemEvent (CFbList *pHandle, TInt aItemIndex, TInt aItemId, TInt aEventType )
{
	if (pHandle == m_pContentList )
	{
		switch (aEventType )
		{
		case EItemSelected:
			if (m_storeType == ETypeLocal )
			{
				ListItemSelectedLocalL (aItemIndex );
			}
			else
			{
				ListItemSelectedRemoteL (aItemIndex );
			}
			break;
		case EPageSingl: //独立页面
			((CFlashbox4MainContainer*) m_pParent)->m_pSoftKeyBar->ShowInfomation (
					R_TIP_GETMORE );
			UpdateOptionMenu (aEventType );
			break;
		case EPageMultFirst: //多-首
		case EPageMultMiddle: //多-中
		case EPageMultLast://多-尾
			((CFlashbox4MainContainer*) m_pParent)->m_pSoftKeyBar->ShowPageNumbers (
					aItemIndex, aItemId );
			UpdateOptionMenu (aEventType );
			break;
		default:

			break;
		}
	}
}

/**
 * 更新选项菜单
 */
void CFbContentWindow::UpdateOptionMenu (TInt aEvent )
{
	CFbList *pOptionMenu =
			((CFlashbox4MainContainer*) m_pParent)->m_pOptionList;
	if (pOptionMenu == NULL )
		return;
	TInt pageupIndex = pOptionMenu->IndexByItmeId (EOptionId_pageup );//上一页位置
	TInt pagedownIndex = pOptionMenu->IndexByItmeId (EOptionId_pagedown );//下一页位置
	switch (aEvent )
	{
	case EPageSingl: //独立页面
		if (pageupIndex >= 0 )
			pOptionMenu->RemoveItem (pageupIndex );
		if (pagedownIndex >= 0 )
			pOptionMenu->RemoveItem (pagedownIndex );
		break;
	case EPageMultFirst: //多-首
	{
		if (pageupIndex >= 0 )
			pOptionMenu->RemoveItem (pageupIndex );
		if (pagedownIndex < 0 )
		{
			//添加"下一页"
			CFbListData *pListItem = new (ELeave) CFbListData (
					EOptionId_pagedown );
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_pagedown );
			pOptionMenu->AddItemL (pListItem, 1 );
			CleanupStack::Pop ();//pListItem		
		}
	}
		break;
	case EPageMultMiddle: //多-中
	{
		if (pagedownIndex < 0 )
		{
			//添加"下一页"
			CFbListData *pListItem = new (ELeave) CFbListData (
					EOptionId_pagedown );
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_pagedown );
			pOptionMenu->AddItemL (pListItem, 1 );
			CleanupStack::Pop ();//pListItem
		}
		if (pageupIndex < 0 )
		{
			//添加"上一页"
			CFbListData *pListItem =
					new (ELeave) CFbListData (EOptionId_pageup );
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_pageup );
			pOptionMenu->AddItemL (pListItem, 2 );
			CleanupStack::Pop ();//pListItem	
		}
	}
		break;
	case EPageMultLast://多-尾
	{
		if (pagedownIndex >= 0 )
			pOptionMenu->RemoveItem (pagedownIndex );
		if (pageupIndex < 0 )
		{
			//添加"上一页"
			CFbListData *pListItem =
					new (ELeave) CFbListData (EOptionId_pageup );
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_pageup );
			pOptionMenu->AddItemL (pListItem, 1 );
			CleanupStack::Pop ();//pListItem
		}
	}
		break;
	case EPageLocal:
	{
		TInt updateIndex = pOptionMenu->IndexByItmeId (EOptionId_update );//上一页位置
		if (updateIndex >= 0 )
			pOptionMenu->RemoveItem (updateIndex );
	}
		break;
	case EPageRemote:
	{
		TInt updateIndex = pOptionMenu->IndexByItmeId (EOptionId_update );//上一页位置
		if (updateIndex < 0 )
		{
			//添加"上一页"
			CFbListData *pListItem =
					new (ELeave) CFbListData (EOptionId_update );
			CleanupStack::PushL (pListItem );
			pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_update );
			pOptionMenu->AddItemL (pListItem, 1 );
			CleanupStack::Pop ();//pListItem
		}
	}
		break;
	case EItemDelete:
		TInt deleteIndex = pOptionMenu->IndexByItmeId (EOptionId_delete );
		if (!m_pContextNodeLocal )
		{
			if (deleteIndex >= 0 )
				pOptionMenu->RemoveItem (deleteIndex );
			return;
		}
		if (m_pContextNodeLocal->ChildCount () == 0 )
		{
			if (deleteIndex >= 0 )
				pOptionMenu->RemoveItem (deleteIndex );
		}
		else
		{
			if (deleteIndex < 0 )
			{
				CFbListData *pListItem = new (ELeave) CFbListData (
						EOptionId_delete );
				CleanupStack::PushL (pListItem );
				pListItem->ConstructL (R_OPTION_BROWSER + EOptionId_delete );
				TInt helpIndex = pOptionMenu->IndexByItmeId (EOptionId_help );
				pOptionMenu->AddItemL (pListItem, helpIndex + 1 );
				CleanupStack::Pop ();//pListItem
			}
		}
		break;
	}
}

////////////////////MWebClientObserver接口函数//////////////
/**
 * WebClientEvent()
 * Called when event occurs in CWebClientEngine.
 * @param aEventDescription: A event in textual format, e.g.
 *                           "Transaction Successful"
 */
void CFbContentWindow::WebClientEvent (const TInt aEvent, TInt /*aSessionId*/, TInt aCode )
{
	switch (aEvent )
	{
	case KHttpTransactionSucceed://连接完成
		this->StopProgressBar ();
		break;
	case KHttpServerError://失败败
		StopProgressBar ();
		break;
	case KHttpTransactionFailed://����������ϴ���
	case KHttpTransactionError:
	case KHttpMHFRunError:
		StopProgressBar ();
		break;
	case KHttpTransactionCancel://����ȡ��
		StopProgressBar ();
		break;
	case KHttpHeaderContentLength://��ݷ�!����֪ͨ�¼�
		TInt len = aCode;
		//更新滚动条数据总长度
		SetProgressBarDataLength (len );
		break;
	case KHttpBodyPartReceived:
		TInt rLen = aCode;
		//更新滚动条进度
		UpdateProgressBar (rLen );
		break;
	case KHttpBodyReceived:
		break;
	case KHttpResponseCode:
#ifdef _DEBUG
				RDebug::Printf("<<<Response Code = %d", aCode);
#endif
		break;
	}
}

/**
 * WebClientHeaderReceived()
 * Called when HTTP header is received.
 * @param aHeaderData: Header field name and value
 */
void CFbContentWindow::WebClientHeaderReceived (const TDesC8& aHeaderFiled, const TDesC8& aHeaderVal,TInt /*aSessionId*/)
{
#ifdef _DEBUG
	RDebug::Printf("< %s : %s", (const char*)aHeaderFiled.Ptr(), (const char*)aHeaderVal.Ptr());
#endif
}

/**
 * WebClientBodyReceivedComplete()
 * Called when a part of the HTTP body is received.
 * @param aBodyData:  Part of the body data received. (e.g. part of
 *                    the received HTML page)
 */
void CFbContentWindow::WebClientBodyReceivedComplete (const TDesC8& aBodyData, TInt aSessionId )
{
	if (aSessionId != m_querySessionId )
		return;

	TFlashboxContentType contentType;
	//保存内容路径
	TFileName filePath (KFbContentsPath );
	AddDrive (filePath );
	//CXmlNode *pInfo;
	if (m_httpQueryType == EGetContents )
	{
		//pInfo = static_cast<CXmlNode*> (m_pListItemSelected->m_pDataBlock );
		//下载内容
		if (m_categoryType == EDong_man_shu_ba )
		{
			//zip压缩包
			filePath.AppendFormat (_L("\\data\\%d\\%d\\%d.zip"),m_categoryType, m_contentsType,
					m_pListItemSelected->GetItemId () );
			contentType = ETypeZip;//zip类型
		}
		else
		{
			//
			filePath.AppendFormat (_L("\\data\\%d\\%d.swf"),
			m_contentsType, m_pListItemSelected->GetItemId () );
			contentType = ETypeSwf;
		}
		
	}
	else//xml更新
	{
		//filePath.AppendFormat (_L("\\data\\%d.xml"),m_contentsType );
		if (m_categoryType != m_contentsType )
		{
			filePath.AppendFormat (_L("\\data\\%d\\%d\\info\\remote.xml"),m_categoryType,
					m_contentsType );
		}
		else
		{
			filePath.AppendFormat (_L("\\data\\%d\\info\\remote.xml"),m_categoryType );
		}
		contentType = ETypeXml; //xml类型
	}

	//检查路径是否存在,如不存在创建
	m_pRfsEngine->EnsurePathExistsL (filePath );
	//保存文件
	m_pRfsEngine->Replace (filePath, aBodyData );

	switch (contentType )
	{
	case ETypeXml:
		m_pXmlHandler->StartParsingL (aBodyData, ETypeRemote );
		return;
	case ETypeZip:
	{
		//zip
		if (m_pDezip == NULL )
		{
			m_pDezip = CDeCompressZip::NewL ();
		}
		CleanupStack::PushL (m_pDezip );
		TFileName targetPath (KFbContentsPath );
		AddDrive (targetPath );
		targetPath.AppendFormat (_L("\\data\\%d\\%d\\%d\\"),m_categoryType, m_contentsType,
				m_pListItemSelected->GetItemId () );
		m_pDezip->WriteFileToSave (filePath, targetPath, ETrue );
		CleanupStack::Pop ();
		
	}
		break;
	case ETypeSwf:
		break;
	}

	// 保存已下载项信息
	CXmlNode
			*pContentInfo =
					static_cast<CXmlNode*> (m_pListItemSelected->m_pDataBlock )->AllocL ();
	if (m_pContextNodeLocal == NULL )
	{
		m_pContextNodeLocal = CXmlNode::NewL (_L8("items"));
	}
	CleanupStack::PushL (m_pContextNodeLocal );
	m_pContextNodeLocal->AddNodeL (pContentInfo );

	TFileName infopath (KFbContentsPath );
	AddDrive (infopath );
	//infopath.AppendFormat (_L("\\data\\%d\\%d.xml"),m_contentsType, m_contentsType);
	if (m_categoryType != m_contentsType )
	{
		infopath.AppendFormat (_L("\\data\\%d\\%d\\info\\local.xml"),m_categoryType,
				m_contentsType );
	}
	else
	{
		infopath.AppendFormat (_L("\\data\\%d\\info\\local.xml"),m_categoryType );
	}
	HBufC8* tmpStr = m_pContextNodeLocal->GetXMLStringL ();
	m_pRfsEngine->Replace (infopath, tmpStr->Des () );
	delete tmpStr;

	CleanupStack::Pop ();

	//过滤已下载
	m_pContentList->RemoveItem (m_pContentList->GetFocusedIndex () );
	m_pListItemSelected = NULL;
	
}

/////////////////////MXmlHandlerObserver接口/////////////////
//文件解析完成
void CFbContentWindow::OnXmlNodeParseCompletedL (TInt aError, CXmlNode *pNode, TInt aSession )
{
#ifdef __WINSCW__
	if (pNode )
	RDebug::Printf (">>>>>OnXmlNodeParseCompletedL->childcount = %d",
			pNode->ChildCount () );
	else
	RDebug::Printf (">>>>>OnXmlNodeParseCompletedL->%s", "pNode == NULL" );
#endif
	if (aError != KErrNone )
		return;

	CXmlNode *pTemp;
	if (aSession == ETypeLocal )
	{
		if (m_pContextNodeLocal )
		{
			delete m_pContextNodeLocal;
			m_pContextNodeLocal = NULL;
		}
		m_pContextNodeLocal = pNode->AllocL ();
		pTemp = m_pContextNodeLocal;

		if (!pTemp || pTemp->ChildCount () <= 0 )
		{
			CAknQueryDialog* dlg = CAknQueryDialog::NewL ();
			HBufC* msg = StringLoader::LoadLC (R_CHANGE_PROMPT_TEXT );
			if (dlg->ExecuteLD (R_CONFIRM_PROMPT, *msg ) )
			{
				CleanupStack::PopAndDestroy (1 );
				SwitchContentL (0 );
				return;
			}
			CleanupStack::PopAndDestroy (1 );
		}
		
		if (m_storeType == aSession )
			SetupListCommonDataL (pTemp );
	}
	else
	{
		pTemp = pNode->ChildNode (_L8("items"));
		SetupListCommonDataL (pTemp );
	}
}

/**
 * 载入List列表数据(普通内容)
 */
void CFbContentWindow::SetupListCommonDataL (CXmlNode *pDataNode )
{
	if (pDataNode == NULL )
		return;

	//清除原有数据
	CleanupStack::PushL (m_pContentList );
	m_pContentList->RemoveAll ();

	/*********************************
	 //item数据格式
	 <item>
	 <id>404</id>
	 <parentid>394</parentid>
	 <itemtype>2</itemtype>
	 <name>水晶之恋时钟屏保</name>
	 <desc>爱TA就</desc>
	 <iconurl>http://wap.wapwu.com/0121114901_M.jpg</iconurl>
	 <size>27kb</size> 
	 <feedesc>2元/次</feedesc>
	 <feeid>3</feeid>
	 <feemethod>WAP</feemethod>
	 <feeurl>Fla3daadkk</feeurl>
	 <feesmscmd></feesmscmd>
	 </item>
	 **********************************/
	TInt childCount = pDataNode->ChildCount ();
	UpdateOptionMenu (EItemDelete );
	for (TInt i = 0; i < childCount; i++ )
	{
		CXmlNode *pItemNode = pDataNode->ChildNode (i );
		if (pItemNode )
		{
			CXmlNode *pIdNode = pItemNode->ChildNode (_L8("id"));
			TInt nodeId = pIdNode ? String2Int (*pIdNode->i_pValue ) : 0;
			//过滤已下载内容
			if (m_storeType == ETypeRemote && pIdNode && pIdNode->i_pValue )
			{
				if (m_pContextNodeLocal != NULL )
				{
					TInt isNodeExist = -1;
					for (TInt i = 0; i < m_pContextNodeLocal->ChildCount (); i++ )
					{
						CXmlNode *pItemLocal = m_pContextNodeLocal->ChildNode (
								i );
						if (pItemLocal )
						{
							isNodeExist = pItemLocal->FindNodeByNodeValue (_L8("id"), *pIdNode->i_pValue );
							if (isNodeExist >= 0 )//已下载
								break;
						}
					}
					
					if (isNodeExist >= 0 )
						continue;
				}
			}

			//数据节点
			CFbListData *pListItem = new (ELeave) CFbListData (nodeId );
			CleanupStack::PushL (pListItem );
			pListItem->m_pDataBlock = pItemNode->AllocL ();

			CXmlNode *pNameNode = pItemNode->ChildNode (_L8("name"));
			CXmlNode *pDesc = pItemNode->ChildNode (_L8("desc"));
			if (pDesc && pDesc->i_pValue )
				pListItem->ConstructL (*pNameNode->i_pValue, *pDesc->i_pValue );
			else
				pListItem->ConstructL (*pNameNode->i_pValue );

			CFbsBitmap *pIcon;
			if (m_storeType == ETypeRemote )
			{
				pIcon = (CEikonEnv::Static ())->CreateBitmapL (
						KFlashboxImagePath, EMbmFlashbox4Icon1 );
			}
			else
			{
				pIcon = (CEikonEnv::Static ())->CreateBitmapL (
						KFlashboxImagePath, EMbmFlashbox4Icon3 );
			}
			//	CFbsBitmap *pIconB = (CEikonEnv::Static ())->CreateBitmapL (KFlashboxImagePath, EMbmFlashbox4Applogo );

			CXmlNode *pUrl = pItemNode->ChildNode (_L8("iconurl"));
			if (pUrl && pUrl->i_pValue )
				pListItem->SetIconUrl (*pUrl->i_pValue );
			pListItem->SetItemIcons (pIcon, NULL/*pIconB*/);
			pListItem->SetDataStoreType (ETypeRemote );
			//生成list项
			m_pContentList->AddItemL (pListItem );
			CleanupStack::Pop ();//pListItem		
		}
	}
	m_pContentList->UpdatePageSatuse ();
	m_pContentList->DrawNow ();
	
	CleanupStack::Pop ();//m_pContentList

}

/**
 * List本地内容点击
 */
void CFbContentWindow::ListItemSelectedLocalL (TInt aIndex )
{
	if (m_pContentList == NULL )
		return;
	CFbListData *pItem = m_pContentList->GetListItem (aIndex );
	if (pItem == NULL )
		return;
	TInt contentId = pItem->GetItemId ();
	
	TFileName filePath (KFbContentsPath );
	AddDrive (filePath );
	TBool isBook = EFalse;//动漫书
	//CXmlNode *pNodeInfo = static_cast<CXmlNode*>(pItem->m_datablock);
	if (m_categoryType == EDong_man_shu_ba )//书吧内容首页
	{
		if (m_contentsType == EDong_man_shu_ba )
		{
			
			//改动TopTab显示
			if (!((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->IsDimmed () )
			{
				//HBufC *pTitle1 = StringLoader::LoadLC(R_TAB_ITEM_TEXT1);
				//HBufC *pTitle = HBufC::NewLC(pTitle1->Length() + pItem->GetTitle()->Length() + 10);
				//pTitle->Des().Copy(pTitle1->Des());
				//pTitle->Des().Append(_L(" :     "));
				//pTitle->Des().Append(pItem->GetTitle()->Des());
				//((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetLabelText(pTitle->Des());
				((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetLabel2Text (
						pItem->GetTitle ()->Des () );
				((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetTabsDimmed (
						ETrue );
				((CFlashbox4MainContainer*) m_pParent)->UpdateOption (
						EOption_Main2Level );
				
				//CleanupStack::PopAndDestroy(2);
			}

			//检索图书分类
			LoadDataL ((TContentsType) contentId, ETypeLocal );
			return;
		}
		else
		{
			//打开图书
			//KFlashBookEntry
			filePath.AppendFormat (_L("\\data\\%d\\%d\\%d\\"),m_categoryType, m_contentsType, contentId );
			filePath.Append (KFlashBookEntry );
			isBook = ETrue;
		}
	}
	else
	{
		filePath.AppendFormat (_L("\\data\\%d\\%d.swf"), m_contentsType, contentId );
	}
	
#ifdef _NOKIA_N95_Flashlite2_ //flashlite 2.0 薄播放器
	if (isBook)
	{
		TUid KFlashliteUid = {270522003};
		TThreadId id;
		RApaLsSession apaLsSession;
		if(apaLsSession.Connect () == KErrNone)
		{
			TApaAppInfo info;
			if (apaLsSession.GetAppInfo (info, KFlashliteUid ) == KErrNone )
			{
				apaLsSession.CreateDocument (filePath, KFlashliteUid, id,
					RApaLsSession::ESwitchFiles );
			}
			else
			{
				OpenFileEmbeddedL(filePath);
			}
			apaLsSession.Close ();
		}
		else
		{
			OpenFileEmbeddedL(filePath);
		}
	}
	else
	{
		OpenFileEmbeddedL(filePath);
	}
#else
	OpenFileEmbeddedL(filePath);
#endif
}

/*
	 * 
 */
void CFbContentWindow::OpenFileEmbeddedL(const TDesC &aFileName)
{
	if (!m_pDocHandler )
	{
		m_pDocHandler = CDocumentHandler::NewL ((CEikProcess*) iEikonEnv->Process () );
		m_pDocHandler->SetExitObserver (this );
	}
	TDataType empty;
	//使用OpenFileL()无法打开mp3播放
	m_pDocHandler->OpenFileEmbeddedL (aFileName, empty );
}

/**
 * List远程内容点击
 */
void CFbContentWindow::ListItemSelectedRemoteL (const TInt aIndex )
{
	if (m_pContentList == NULL )
		return;

	m_pListItemSelected = m_pContentList->GetListItem (aIndex );
	if (m_pListItemSelected == NULL )
		return;

	TInt contentId = m_pListItemSelected->GetItemId ();
	if (m_categoryType == EDong_man_shu_ba )//书吧内容首页
	{
		if (m_contentsType == EDong_man_shu_ba )
		{
			if (!((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->IsDimmed () )
			{
				((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetLabel2Text (
						m_pListItemSelected->GetTitle ()->Des () );
				((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetTabsDimmed (
						ETrue );
				((CFlashbox4MainContainer*) m_pParent)->UpdateOption (EOption_Main2Level );
			}
			// 保存目录信息息
			CXmlNode *pContentInfo =
							static_cast<CXmlNode*> (m_pListItemSelected->m_pDataBlock )->AllocL ();
			
						
			if (m_pContextNodeLocal == NULL )
			{
				m_pContextNodeLocal = CXmlNode::NewL (_L8("items"));
			}
			CleanupStack::PushL (m_pContextNodeLocal );
			m_pContextNodeLocal->AddNodeL (pContentInfo );
			
			TFileName infopath (KFbContentsPath );
			AddDrive (infopath );
			//infopath.AppendFormat (_L("\\data\\%d\\%d.xml"),m_contentsType, m_contentsType);
			infopath.AppendFormat (_L("\\data\\%d\\info\\local.xml"),m_categoryType );
			HBufC8 *pStr = m_pContextNodeLocal->GetXMLStringL ();
			m_pRfsEngine->EnsurePathExistsL (infopath);
			m_pRfsEngine->Replace (infopath, pStr->Des () );
			CleanupStack::Pop ();//m_pContextNodeLocal
			delete pStr;
			
			//检索图书分类
			//LoadDataL ((TContentsType) contentId, ETypeRemote );
			//m_pLeftTabgroup->SetActiveTabByIndexL (0 );//切到本地目录
			LoadDataL ((TContentsType) contentId, ETypeRemote);
		}
		else
		{
			//下载内容
			QueryDataByHttpL (contentId, EGetContents );
		}
		
	}
	else
	{
		//下载内容
		QueryDataByHttpL (contentId, EGetContents );
	}
}

//MAknServerAppExitObserver 
void CFbContentWindow::HandleServerAppExit (TInt /*aReason*/ )
{
	if (m_pDocHandler )
	{
		delete m_pDocHandler;
		m_pDocHandler = NULL;
	}
}

/**
 * 开始显示滚动条
 */
void CFbContentWindow::StartToShowProgressBar ()
{
	if (m_pProgressBar == NULL )
	{
		m_pProgressBar
				= CFbProgressBar::NewL (*this, KFbProgressBarHttpGetRect );
		m_pProgressBar->SetShowTipTextL (
				R_PROGRESS_DOWNLOAD, KFbTabgroupTopColor );
		m_pProgressBar->SetTotalDataLength (100000 );
		m_pProgressBar->UpdateRunningStep (100 );
	}
	m_pParent->SetDimmed (ETrue );
	((CFlashbox4MainContainer*) m_pParent)->SetSoftKeyBarL (
			ESoftkeybar_Null_Cancel );

	m_pProgressBar->MakeVisible (ETrue );
	m_pProgressBar->DrawNow ();
}

/**
 * 设置滚动条的数据总量
 */
void CFbContentWindow::SetProgressBarDataLength (TInt aLen )
{
	if (m_pProgressBar )
		m_pProgressBar->SetTotalDataLength (aLen );
}

/**
 * 更新滚动条
 * step 增加步长
 */
void CFbContentWindow::UpdateProgressBar (TInt step )
{
	if (m_pProgressBar )
		m_pProgressBar->UpdateRunningStep (step );
}

/**
 * 停止滚动条
 */
void CFbContentWindow::StopProgressBar ()
{
	if (m_pProgressBar )
	{
		m_pProgressBar->MakeVisible (EFalse );
		delete m_pProgressBar;
		m_pProgressBar = NULL;
	}

	m_pParent->SetDimmed (EFalse );
	((CFlashbox4MainContainer*) m_pParent)->SetSoftKeyBarL (ESoftkeybar_Option_Local );
	/*if (m_categoryType == EDong_man_shu_ba && m_contentsType != EDong_man_shu_ba)
	 {
	 //书吧内容
	 ((CFlashbox4MainContainer*)m_pParent)->m_pTopTabgroup->SetTabsDimmed(EFalse);
	 }
	 */
}

/**
 * from CCoeControl
 */
void CFbContentWindow::MakeVisible (TBool aVisible )
{
	CCoeControl::MakeVisible (aVisible );

	m_pLeftTabgroup->MakeVisible (aVisible );
	m_pContentList->MakeVisible (aVisible );
}

/**
 * 取得栏目类别
 */
TInt CFbContentWindow::GetCategoryType ()
{
	return m_categoryType;
}

/*
 * Get the stored type!
 */
TInt CFbContentWindow::GetStoreType ()
{
	return m_storeType;
}

/**
 * 处理选项菜单消息！
 */
void CFbContentWindow::HandleParentOptionMsg (TInt aOptionId )
{
	switch (aOptionId )
	{
	case EOptionId_open://打开
		ListItemEvent (m_pContentList, m_pContentList->GetFocusedIndex (), -1,
				EItemSelected );
		break;
	case EOptionId_pageup://上一页
		m_pContentList->PrevListPage ();
		break;
	case EOptionId_pagedown://下一页
		m_pContentList->NextListPage ();
		break;
	case EOptionId_return://返回
		ChangeToCategory ((TContentsType) m_categoryType, ETypeLocal );
		((CFlashbox4MainContainer*) m_pParent)->UpdateOption (EOption_Main );
		((CFlashbox4MainContainer*) m_pParent)->m_pTopTabgroup->SetTabsDimmed (
				EFalse );
		//((CFlashbox4MainContainer*) m_pParent)->MakeAllVisableExceptOpt(ETrue);
		((CFlashbox4MainContainer*) m_pParent)->DrawNow ();
		break;
	case EOptionId_update://更新xml
		if (m_storeType == ETypeRemote )
		{
			//从网上更新
			QueryDataByHttpL (m_contentsType, EQueryContents );
		}
		break;
	case EOptionId_delete:
		CAknQueryDialog* dlg = CAknQueryDialog::NewL ();
		if (dlg->ExecuteLD (R_CONFIRM_PROMPT ) )
		{
			CFbListData *pItem = m_pContentList->GetListItem (
					m_pContentList->GetFocusedIndex () );
			if (!pItem )
				return;
			CRfsEngine* pRfsEngine = CRfsEngine::NewLC ();
			TFileName tmpFileName (KFbContentsPath );
			AddDrive (tmpFileName );

			tmpFileName.AppendFormat (_L("\\data\\%d\\"),m_categoryType );
			tmpFileName.AppendFormat (_L("%d.swf"), pItem->GetItemId () );
			pRfsEngine->DeleteFile (tmpFileName );
			CleanupStack::PopAndDestroy ();
			//m_pContextNodeLocal->ChildNode(_L8("id"));
			for (TInt i = 0; i < m_pContextNodeLocal->ChildCount (); i++ )
			{
				CXmlNode *pItemLocal = m_pContextNodeLocal->ChildNode (i );
				TInt idelId = String2Int (*(pItemLocal->ChildNode (_L8("id"))->i_pValue) );
				if (idelId == pItem->GetItemId () )
				{
					m_pContextNodeLocal->DeleteNode (i );
					break;
				}
			}
			TFileName infopath (KFbContentsPath );
			AddDrive (infopath );
			if (m_categoryType != m_contentsType )
			{
				infopath.AppendFormat (_L("\\data\\%d\\%d\\info\\local.xml"),m_categoryType,
						m_contentsType );
			}
			else
			{
				infopath.AppendFormat (_L("\\data\\%d\\info\\local.xml"),m_categoryType );
			}
			HBufC8* tmpStr = m_pContextNodeLocal->GetXMLStringL ();
			m_pRfsEngine->EnsurePathExistsL (infopath);
			m_pRfsEngine->Replace (infopath, tmpStr->Des () );
			delete tmpStr;

			TInt delItemIndex = m_pContentList->IndexByItmeId (
					pItem->GetItemId () );
			m_pContentList->RemoveItem (delItemIndex );
			m_pContentList->DrawNow ();
			
			break;
		}
		
	}
}

void CFbContentWindow::HandleParentEjectOptionMsg (TInt aEjectOptionId )
{
	switch (aEjectOptionId )
	{
	case 0:
		ListItemSelectedLocalL (m_pContentList->GetFocusedIndex () );
		break;
	}
}

void CFbContentWindow::ClientBodyReceived (const TDesC8& aBodyData, TBool aIsLast )
{
	
}

